\section{VHDL}
\label{sec:vhdl}

\subsection{Encoder}
	\subsubsection{Quadrature encoding fundamentals}
	In order to keep track of the position and direction of the rotating wheel quadrature encoding is used. Quadrature encoding is a technique capable of high resolution and high precision measurement which can operate for a wide range of speeds. The basic idea of a quadrature encoder is shown in figure \ref{fig:vhdl_enc}. Here it can be seen that there are two sensors and two tracks. In the case of an optical sensor, the dark part reflects less light than the light part of the track. Thus, a sensor can detect either a light part or dark part of the track. The JIWY setup uses two HEDS-5540 A11 encoders\citep{HEDS5540} for this. Now, by offsetting the phase of the two tracks by ninety degrees, it is possible to determine the change in position and therefore the direction of the wheel.
	
	\begin{figure}[h]
		\centering
			\includegraphics[width=0.8\textwidth]{images/quad_encoder.png}
		\caption{Fundamentals of a quadrature encoder \cite{prototalk:quad}}
		\label{fig:vhdl_enc}
	\end{figure}
	
	This calculation of the direction is done as follows. The output of the two sensors, which is two bits per cycle, is usually called Channel A and Channel B. These two bits define four possible states in which the encoder can reside. Because the two tracks have a ninety degrees offset, it is not possible that both state bits switch at the same time. Only one bit can change at a time. Thus, by comparing the current state to the previous state the direction can be determined. These changes are summed up in table \ref{tab:vhdl_enc}.
	
% Table generated by Excel2LaTeX from sheet 'Blad1'
	\begin{table}[htbp]
		\centering
		\caption{Truth table for quadrature encoding}
			\begin{tabular}{ccccc}
			\toprule
			\multicolumn{2}{c}{\textbf{Current state}} & \multicolumn{2}{c}{\textbf{Next state}} & \textbf{} \\
			\midrule
			\textbf{CH A} & \textbf{CH B} & \textbf{CH A} & \textbf{CH B} & \textbf{Direction} \\
			\multirow{2}[1]{*}{High} & \multirow{2}[1]{*}{High} & High  & Low   & Reverse \\
						&       & Low   & High  & Forward \\
			\multirow{2}[0]{*}{High} & \multirow{2}[0]{*}{Low} & High  & High  & Reverse \\
						&       & Low   & Low   & Forward \\
			\multirow{2}[0]{*}{Low} & \multirow{2}[0]{*}{High} & Low   & Low   & Reverse \\
						&       & High  & High  & Forward \\
			\multirow{2}[1]{*}{Low} & \multirow{2}[1]{*}{Low} & High  & Low   & Reverse \\
						&       & Low   & High  & Forward \\
			\bottomrule
			\end{tabular}%
		\label{tab:vhdl_enc}%
	\end{table}%

	\subsubsection{Implementation}
	Implementation of this encoder in VHDL is straightforward. The code can be found in listing \ref{lst:encoder}. Obviously, the inputs consist of the clock, reset, Channel A and Channel B. The output was chosen to be a value large enough to count all rotations without overflow. The setup has 500 CPR, but there are two tracks and a state change happens twice per count. Therefore, a value of at least 2000 is needed. The output is therefore chosen to be eleven bits wide. Note that even for larger CPR it could still work correctly, however then overflow detection is needed in software to compensate for the overflow in the hardware. Overflow detection is also needed if the starting point of the rotating wheel is not close to the center (for signed representation), because then it could overflow at the endpoints.
	
	Now that the inputs and outputs are defined, the architecture can be specified. Basically, it is nothing more than a state machine as specified in table \ref{tab:vhdl_enc}. At the rising edge of the clock, the last two states are compared to obtain a difference. Then, the counter is updated with this difference. Note that directly after a reset the previous state is not defined well, because it is reset to zero. Therefore, it is neccessary to first wait two cycles to collect two states. After that, the difference can be calculated again. For this, the variable \emph{after\_reset} is used. Last, the current value of Channel A and Channel B is saved for the next cycle. If the comparison between the previous and current state is one that does not exist in table \ref{tab:vhdl_enc}, it is ignored. This is something that should normally not occur, as it is an invalid transition, however it is possible that it happens because of a malfunction in the sensors.
	
	To use this module with the NIOS, a mapping to the AVALON bus is needed. For this, the standard template provided by \emph{ESL\_bus\_demo} was used. This makes it possible to let the processor read the value of the encoder. Because the processor only reads 32 bits wide addresses, the 11 bit counter is sign extended to 32 bits.
	
	\subsubsection{Testing}
	The encoder was tested both in simulation with a testbench and live on the FPGA. The testbench simulates a wheel which first moves in one direction, then stops and rotates back twice as far. After that, several bits of the channels are flipped at once, which should not lead to a change in count. The testbench file can be found in the file \emph{vhdl/tb\_quadrature.vhd}. Part of the result of this test is shown in figure \ref{fig:quad_simulation}. The simulation behaves as expected.
	
	\begin{figure}
		\centering
			\includegraphics[width=1.00\textwidth]{images/simulation_quad.png}
		\caption{Simulation results of quadrature encoder}
		\label{fig:quad_simulation}
	\end{figure}
	
	For the test on the FPGA, the VHDL was synthesized and some code was written for the NIOS processor to read the value of the counter every 100 ms. The code was run after which the rotating wheel was manually moved to check if the counter was updated accordingly. One important test was to check if it was accurate, thus if the same position of the wheel did not lead to different values of the counter. This was tested by moving the wheel to an endpoint, writing down the counter value there, then making other movements with the wheel, after which it was moved back to the endpoint. If it is working correctly, the counter value at the endpoint should not change. In our tests, it was found that the counter value did not change significantly, but sometimes it did differ by one.
	
\subsection{PWM}
	Pulse Width Modulation (PWM) is a technique that is used to control the power to an electrical device, in this case the motor that controls the rotating wheels. Here, two signals are used to control an H-bridge, one for direction and one for duty cycle. The H-bridge is turned on when either both signals are high or both signals are low. Thus, the power to the motor, and therefore the speed of the motor, can be controlled by setting the two output signals direction and duty cycle.
	
	\subsubsection{Implementation}
	Again, implementation of the module is pretty straightforward. The code can be found in listing \ref{lst:pwm}. The inputs are a clock, reset, direction and duty cycle where the duty cycle is of type \emph{std\_logic\_vector}. The size of this should be such that the frequency at which the H-bridge switches is high enough so that humans cannot hear switching, yet low enough so that the switching is power efficient. This means that the frequency range for which the H-bridges work well is 20-50kHz. Lower frequencies result in annoying switching beeps, higher frequencies result in inefficient switching behaviour. In our design, it was chosen to use approximately 50 KHz for our PWM signal, which means that the duty cycle signal should be able to hold values up to $\frac{clock\_freq}{pwm\_freq}=\frac{50 MHz}{50 KHz} = 1000$. Thus, 10 bits are needed for this. The outputs of the design are the PWM signal and the direction signal which both go to the H-bridge.
	
	It can be seen that the direction signal is not actually used in the implementation, because it is directly linked from input to output. It is also possible to omit it completely, or to only provide one input which includes the direction (ones complement notation). However, since none of these options has any decisive performance advantage, we decided it was the cleanest option to just include the direction signal in the design and link it from input to output. This also provides a way to keep the entity declaration the same when something in the H-bridge changes which could require processing of the direction signal as well.
	
	The actual implementation is just a counter that counts from 0 to 1023. The PWM output signal is defined as 1 whenever the counter is smaller than the input duty cycle and 0 whenever the counter is equal or larger. Thus, when the input duty cycle is zero, the output will always be zero. When the input is duty cycle is 1023, the output will be a 1 $\frac{1023}{1024}$ of the time.
	
	Just as for the encoder, an interface file was also written for the PWM. This makes it possible to set the PWM from the NIOS processor.
	
	\subsubsection{Testing}
	The PWM was tested both in simulation with a testbench and live on the FPGA. The testbench simulates different inputs for the PWM. The testbench file can be found in the file \emph{vhdl/tb\_pwm.vhd}. Simulating the testbench leaded to the expected results, as shown in figure \ref{fig:pwm_simulation}.
	
	\begin{figure}
		\centering
			\includegraphics[width=1.00\textwidth]{images/simulation_pwm.png}
		\caption{Simulation results of PWM}
		\label{fig:pwm_simulation}
	\end{figure}
	
	\begin{figure}
		\centering
			\includegraphics[width=1.00\textwidth]{images/pwm_ff.jpg}
		\caption{Measurements of PWM}
		\label{fig:pwm_ff}
	\end{figure}
	
	With a properly simulating PWM, it was time to put it on the FPGA and test it for real. The PWM was set from the NIOS processor to several different values while the output signal was checked at the oscilloscope. One of the results is shown in figure \ref{fig:pwm_ff}. This shows the output when the duty cycle is set to \emph{0xff}. This corresponds to 25\% which is roughly equivalent to what is measured. Also, the output was connected to the H-bridge. This worked correctly for different values of direction and duty cycle.
	